package bootstrap

import (
	memberModel "tdy-backend/app/member/model"
	panoramicModel "tdy-backend/app/panoramic/model"
	"tdy-backend/global"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

func Gorm() *gorm.DB {
	return GormMysql()
}

func GormMysql() *gorm.DB {
	dsn := global.TYD_CONFIG.GetString("database.user") + ":" + global.TYD_CONFIG.GetString("database.pass") + "@tcp(" + global.TYD_CONFIG.GetString("database.host") + ":" + global.TYD_CONFIG.GetString("database.port") + ")/" + global.TYD_CONFIG.GetString("database.table") + "?charset=" + global.TYD_CONFIG.GetString("database.charset") + "&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: true,
		Logger:                                   logger.Default.LogMode(logger.Info),
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   global.TYD_CONFIG.GetString("database.tablePrefix"), // table name prefix, table for `User` would be `t_users`
			SingularTable: true,
		},
	})
	if err != nil {
		panic("数据库链接失败")
	}

	db.AutoMigrate(
		&memberModel.Asset{},
		&memberModel.Member{},
		&panoramicModel.Group{},
		&panoramicModel.Material{},
		&panoramicModel.Scene{},
		&panoramicModel.Works{},
		&panoramicModel.Spot{},
	)

	return db
}
